package com.rdgk.newtech.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * @author tens
 */
public class WordUtil {

    /**
     * 根据freemarker生成word文档并存到指定目录
     * @param wordFilePath word文件生成的目录
     * @param wordFileName word文件名
     * @param templatePath 模板文件所在的目录
     * @param templateFileName 模板文件名
     * @param beanParams 生成word文件所需要的模板数据
     * @return
     */
    public static Boolean writeWordReport(String wordFilePath,String wordFileName,
                                          String templatePath,String templateFileName, Map<String, Object> beanParams) {
        Configuration config = new Configuration(Configuration.getVersion());
        Writer out = null;
        try {
            config.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = config.getTemplate(templateFileName, "UTF-8");

            //获取文件目录，如果不存在则创建
            String filePath = "";
            int index = wordFilePath.lastIndexOf(File.separator);
            if (index != wordFilePath.length() - 1) {
                filePath = wordFilePath + File.separator;
            } else {
                filePath = wordFilePath;
            }
            File file1 = new File(filePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }

            //输出文件
            File file = new File(filePath + wordFileName);
            FileOutputStream fos = new FileOutputStream(file);
            out = new OutputStreamWriter(fos, "UTF-8");
            template.process(beanParams, out);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
